package com.lzx.shop.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzx.shop.dataobject.CategoryDO;
import com.lzx.shop.dataobject.ProductDO;
import com.lzx.shop.model.Result;
import com.lzx.shop.service.CategoryService;
import com.lzx.shop.service.ProductService;
import com.lzx.shop.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName CategoryApi.java
 * @Description TODO
 * @createTime 2021年03月21日 11:56:00
 */
@Api(tags = "CategoryApidd",description = "类目管理")
@RestController
@RequestMapping("/category")
public class CategoryApi {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;

    @ApiOperation("查询所有类目")
    @GetMapping("/list")
    public Result listCategory(@RequestParam(value = "need",required = false) boolean need){

        List<CategoryDO> categoryDOList = categoryService.findAll();


        if (need){
            categoryDOList.forEach(categoryDO -> {
                IPage<ProductDO> productDOIPage = productService.
                        selectPage(new Page<>(1, 6), new QueryWrapper<ProductDO>().eq("category_id", categoryDO.getId()));
                categoryDO.setProductDOList(productDOIPage.getRecords());
            });
        }

        return ResultUtil.customResultParam(true,"0","成功",categoryDOList);
    }

    @ApiOperation("插入类目")
    @PostMapping("/save")
    public Result save(@RequestBody CategoryDO categoryDO){
        if (categoryDO==null){
            return ResultUtil.paramError();
        }

        return ResultUtil.success(categoryService.save(categoryDO));
    }

    @ApiOperation("更新类目")
    @PostMapping("/update")
    public Result update(@RequestBody CategoryDO categoryDO){
        if (categoryDO == null){
            return ResultUtil.paramError();
        }
        return  ResultUtil.success(categoryService.update(categoryDO));
    }

    @ApiOperation("删除类目")
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable("id") String id){
        if (StringUtils.isBlank(id)){
            return ResultUtil.paramError();
        }
        return  ResultUtil.success(categoryService.DeleteById(id));
    }
}
